<template>
  <div class="comment-management">
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="评分">
          <el-select v-model="searchForm.rating" placeholder="请选择评分" clearable>
            <el-option label="全部" :value="null" />
            <el-option label="1星" :value="1" />
            <el-option label="2星" :value="2" />
            <el-option label="3星" :value="3" />
            <el-option label="4星" :value="4" />
            <el-option label="5星" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否匿名">
          <el-select v-model="searchForm.isAnonymous" placeholder="请选择" clearable>
            <el-option label="全部" :value="null" />
            <el-option label="匿名" :value="1" />
            <el-option label="非匿名" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 搜索条件标签 -->
    <div class="search-tags" v-if="hasSearchConditions">
      <span class="search-tags-label">搜索条件：</span>
      <el-tag 
        v-if="searchForm.rating !== null" 
        closable 
        @close="clearSearchRating"
        class="search-tag"
      >
        评分：{{ searchForm.rating }}星
      </el-tag>
      <el-tag 
        v-if="searchForm.isAnonymous !== null" 
        closable 
        @close="clearSearchAnonymous"
        class="search-tag"
      >
        是否匿名：{{ searchForm.isAnonymous === 1 ? '匿名' : '非匿名' }}
      </el-tag>
    </div>

    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <!-- <el-table-column prop="id" label="评论ID" width="100" /> -->
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column prop="orderId" label="订单ID" width="100" />
      <el-table-column prop="content" label="评论内容" min-width="200" show-overflow-tooltip />
      <el-table-column prop="images" label="评论图片" width="120">
        <template #default="{ row }">
          <div v-if="row.images && row.images.length > 0" class="comment-images">
            <el-image 
              v-for="(image, index) in row.images"
              :key="index"
              :src="image"
              :preview-src-list="row.images"
              fit="cover"
              class="comment-image"
            />
          </div>
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="rating" label="评分" width="100">
        <template #default="{ row }">
          <el-rate
            v-model="row.rating"
            disabled
            show-score
            text-color="#ff9900"
          />
        </template>
      </el-table-column>
      <el-table-column prop="isAnonymous" label="是否匿名" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isAnonymous === 1 ? 'info' : 'success'">
            {{ row.isAnonymous === 1 ? '匿名' : '非匿名' }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="createTime" label="创建时间" width="180" /> -->
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            link 
            @click="handleEdit(row)"
          >
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加修改评论对话框 -->
    <el-dialog
      title="修改评论"
      v-model="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="padding: 0 20px"
      >
        <el-form-item label="评论内容" prop="content">
          <el-input 
            v-model="form.content" 
            type="textarea" 
            :rows="4"
            placeholder="请输入评论内容" 
          />
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-rate
            v-model="form.rating"
            :max="5"
            show-score
            text-color="#ff9900"
          />
        </el-form-item>
        <el-form-item label="是否匿名" prop="isAnonymous">
          <el-switch
            v-model="form.isAnonymous"
            :active-value="1"
            :inactive-value="0"
            active-text="匿名"
            inactive-text="非匿名"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCommentList, updateComment } from '@/api/comment'

// 搜索表单
const searchForm = reactive({
  rating: null,
  isAnonymous: null
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 判断是否有搜索条件
const hasSearchConditions = computed(() => {
  return searchForm.rating !== null || 
         searchForm.isAnonymous !== null
})

// 获取评论列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getCommentList({
      rating: searchForm.rating,
      isAnonymous: searchForm.isAnonymous,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    if (res.code === 1) {
      const { records, total: totalCount } = res.data
      // 兼容 images 字段为字符串
      tableData.value = records.map(item => {
        if (typeof item.images === 'string') {
          item.images = item.images
            ? item.images.split(',').map(url => url.trim()).filter(Boolean)
            : []
        }
        return item
      })
      total.value = totalCount
    } else {
      ElMessage.error(res.msg || '获取评论列表失败')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.rating = null
  searchForm.isAnonymous = null
  handleSearch()
}

// 清除搜索条件
const clearSearchRating = () => {
  searchForm.rating = null
  handleSearch()
}

const clearSearchAnonymous = () => {
  searchForm.isAnonymous = null
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

// 表单对话框
const dialogVisible = ref(false)
const formRef = ref(null)
const form = reactive({
  orderId: null,
  content: '',
  rating: 5,
  images: '',
  isAnonymous: 0
})

// 表单验证规则
const rules = {
  content: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 1, max: 500, message: '评论内容长度在 1 到 500 个字符', trigger: 'blur' }
  ],
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' }
  ]
}

// 修改评论
const handleEdit = (row) => {
  Object.assign(form, {
    orderId: row.orderId,
    content: row.content,
    rating: row.rating,
    images: Array.isArray(row.images) ? row.images.join(',') : row.images,
    isAnonymous: row.isAnonymous
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保所有必填字段都有值
        if (!form.orderId) {
          ElMessage.error('订单ID不能为空')
          return
        }
        if (!form.content?.trim()) {
          ElMessage.error('评论内容不能为空')
          return
        }
        if (!form.rating) {
          ElMessage.error('请选择评分')
          return
        }

        const res = await updateComment(form)
        if (res.code === 1) {
          ElMessage.success('修改成功')
          dialogVisible.value = false
          getList()
        } else {
          ElMessage.error(res.msg || '修改失败')
        }
      } catch (error) {
        console.error('修改评论失败:', error)
        ElMessage.error('修改评论失败')
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.comment-management {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-tags {
  margin-bottom: 20px;
}

.search-tags-label {
  margin-right: 8px;
  color: #606266;
}

.search-tag {
  margin-right: 8px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.comment-images {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.comment-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  cursor: pointer;
}
</style> 